<?php
/**
 * @version		$Id: k2mart.php 73 2010-09-17 11:22:42Z lefteris.kavadas $
 * @package		K2mart
 * @author    	JoomlaWorks http://www.joomlaworks.gr
 * @copyright	Copyright (c) 2006 - 2010 JoomlaWorks, a business unit of Nuevvo Webware Ltd. All rights reserved.
 * @license		Commercial - This code cannot be redistributed without permission from Nuevvo Webware Ltd.
 */

// no direct access
defined('_JEXEC') or die('Restricted access');

JLoader::register('K2Plugin', JPATH_ADMINISTRATOR.DS.'components'.DS.'com_k2'.DS.'lib'.DS.'k2plugin.php');

class plgK2K2mart extends K2Plugin {

    var $pluginName = 'k2mart';
    var $pluginNameHumanReadable = 'K2mart';

    function plgK2K2mart(& $subject, $config) {
        parent::__construct($subject, $config);
    }

    function isInstalled() {
        jimport('joomla.filesystem.file');
        return JFile::exists(JPATH_SITE.DS.'components'.DS.'com_virtuemart'.DS.'virtuemart.php');
    }

    function onAfterK2Save(&$item, $isNew) {

        $mainframe = &JFactory::getApplication();
        $db = &JFactory::getDBO();

        //Check if Virtuemart is installed
        if (!$this->isInstalled()) {
            return;
        }

        //Include Virtuemart class
        require_once(JPATH_SITE.DS.'components'.DS.'com_virtuemart'.DS.'virtuemart_parser.php');
        include_class('product') ;

        //Bind Variables
        $vars = JRequest::get('post');
        $productID = JRequest::getInt('product_id');
        $vars['product_id'] = $productID;
        $vars['product_name'] = $item->title;

        //Handle assignment
        if(JRequest::getBool('vmAssign')){
            $query = "INSERT INTO #__k2mart VALUES ('', {$productID}, {$item->id}) ON DUPLICATE KEY UPDATE productID={$productID}, itemID={$item->id}";
            $db->setQuery($query);
            $db->query();
        }

        //Handle unassignment
        if(JRequest::getBool('vmUnassign')){
            if($item->id && $productID){
                $query = "DELETE FROM #__k2mart WHERE productID={$productID} AND itemID={$item->id} LIMIT 1";
                $db->setQuery($query);
                $db->query();
            }
            return;
        }

        //Handle remove
        if(JRequest::getBool('vmRemove')){
            if($productID){
                $query = "DELETE FROM #__k2mart WHERE productID={$productID} LIMIT 1";
                $db->setQuery($query);
                $db->query();
                $ps_product->delete_product($productID, $vars);
            }
            return;
        }

        //Handle form
        if(JRequest::getVar('product_sku', NULL)){

            ob_start();
            if($vars['product_id']){
                $ps_product->update($vars);
            }
            else {
                $ps_product->add($vars);
                $productID = $vars['product_id'];
                $query = "INSERT INTO #__k2mart VALUES ('', {$productID}, {$item->id}) ON DUPLICATE KEY UPDATE productID={$productID}, itemID={$item->id}";
                $db->setQuery($query);
                $db->query();
            }
            $results = ob_get_clean();
            $mainframe->enqueueMessage($results);
            return;
        }

    }


    function onK2AfterDisplayContent(&$item, &$params, $limitstart) {

        $mainframe = &JFactory::getApplication();
        jimport('joomla.filesystem.file');
        if (!$this->isInstalled() || $mainframe->isAdmin()) {
            return;
        }

        //Get params
        $this->params = &JComponentHelper::getParams('com_k2mart');

        //Get application variables
        $option = JRequest::getCmd('option');
        $view = JRequest::getCmd('view');

        //Define the layout
        if($option=='com_k2' && $view=='item'){
            $layout = 'item';
        }
        else {
            $layout = 'listing';
        }
        if(array_key_exists('moduleclass_sfx',$params->toArray())){
            $layout = 'module';
        }

        //Check for disabled layout
        if($this->params->get($layout.'LayoutDisabled')){
            return;
        }

        //Get product ID
        $db = &JFactory::getDBO();
        $query = "SELECT productID FROM #__k2mart WHERE itemID=".$item->id;
        $db->setQuery($query, 0, 1);
        $productID = $db->loadResult();

        if(is_null($productID)){
            return;
        }

        //Check for non-registered users
        $user = &JFactory::getUser();
        if($this->params->get('membersOnlyCart') && $user->guest){
            $this->params->set($layout.'ProductAddToCart', 0);
        }

        //Load language
        JPlugin::loadLanguage('plg_k2_k2mart', JPATH_ADMINISTRATOR);

        //Include Virtuemart classes
        global $ps_product, $ps_product_attribute, $ps_product_type, $VM_LANG, $sess;
        require(JPATH_SITE.DS.'components'.DS.'com_virtuemart'.DS.'virtuemart_parser.php');
        include_class('product');
        $VM_LANG->load('shop');

        //Get Product
        $row = $ps_product->get($productID);

        //If product is unpublished or null return
        if(is_null($row) || $row->f('product_publish')!='Y'){
            return;
        }

        //Load scripts and styles
        if(!isset($this->head)){
            JHTML::_('behavior.mootools');
            JHTML::_('behavior.modal');
            $document = &JFactory::getDocument();
            $document->addScript(VM_THEMEURL.'theme.js');
            $document->addStyleSheet(VM_THEMEURL.'theme.css');
            $document->addScriptDeclaration('var cart_title = "'.$VM_LANG->_('PHPSHOP_CART_TITLE').'";var ok_lbl="'.$VM_LANG->_('CMN_CONTINUE').'";var cancel_lbl="'.$VM_LANG->_('CMN_CANCEL').'";var notice_lbl="'.$VM_LANG->_('PEAR_LOG_NOTICE').'";var live_site="'.JURI::root().'";');
            $document->addScript( JURI::root().'components/'. VM_COMPONENT_NAME .'/js/mootools/mooPrompt.js');
            $document->addStyleSheet( JURI::root().'components/'. VM_COMPONENT_NAME .'/js/mootools/mooPrompt.css');
            if(JFile::exists(JPATH_SITE.DS.'templates'.DS.$mainframe->getTemplate().DS.'html'.DS.'k2mart'.DS.'css'.DS.'style.css')){
                $document->addStyleSheet( JURI::root().'templates/'.$mainframe->getTemplate().'/html/k2mart/css/style.css');
            }
            else {
                $document->addStyleSheet( JURI::root().'plugins/k2/k2mart/tmpl/css/style.css');
            }
            $this->head = true;
        }

        //Get Itemid
        $Itemid = $sess->getShopItemid();

        //Create product object
        $product = new JObject();
        $product->set('id', $row->f('product_id'));
        $product->set('name', $row->f('product_name'));
        $product->set('sku', $row->f('product_sku'));
        $product->set('url', $row->f('product_url'));
        $product->set('vendorLink','');
        $product->set('manufacturerLink','');
        $product->set('price','');
        $product->set('unit',$row->f('product_unit'));
        $product->set('packaging','');
        $product->set('box','');
        $product->set('stock', $row->f('product_in_stock'));
        $product->set('type','');
        $product->set('length', $row->f('product_length'));
        $product->set('width', $row->f('product_width'));
        $product->set('height', $row->f('product_height'));
        $product->set('weight', $row->f('product_weight'));
        $product->set('dimensionUnit', $row->f("product_lwh_uom"));
        $product->set('weightUnit', $row->f("product_weight_uom"));
        $product->set('availableDate', $row->f("product_available_date"));
        $product->set('shipping', $row->f("product_availability"));

        //Get Vendor
        if($this->params->get($layout.'ProductVendor')){
            $product->set('vendorID', $ps_product->get_vendor_id($productID));
            $product->set('vendorName', $ps_product->get_vendorname($productID));
            $product->set('vendorLink', JRoute::_("index2.php?option=com_virtuemart&page=shop.infopage&vendor_id={$product->vendorID}&output=lite&Itemid={$Itemid}"));
        }

        //Get manufacturer
        if($this->params->get($layout.'ProductManufacturer')){
            $product->set('manufacturerID', $ps_product->get_manufacturer_id($productID));
            $product->set('manufacturerName', $ps_product->get_mf_name($productID));
            if( $product->manufacturerID && !empty($product->manufacturerName) ) {
                $product->set('manufacturerLink', JRoute::_("index2.php?option=com_virtuemart&page=shop.manufacturer_page&manufacturer_id={$product->manufacturerID}&output=lite&Itemid={$Itemid}"));
            }
        }

        //Get price
        if (_SHOW_PRICES == '1' && $this->params->get($layout.'ProductPrice')) {
            $product->set('price', $ps_product->show_price( $productID ));
        }

        //Get packaging
        if ($row->f("product_packaging")) {
            $product->packaging = $row->f("product_packaging") & 0xFFFF;
            $product->box = ($row->f("product_packaging") >> 16) & 0xFFFF;
        }

        //Get type
        if($this->params->get($layout.'ProductType')){
            if ($row->f('product_parent_id')!=0 && !$ps_product_type->product_in_product_type($productID)) {
                $product->type = $ps_product_type->list_product_type($row->f('product_parent_id'));
            }
            else {
                $product->type = $ps_product_type->list_product_type($productID);
            }
        }

        //Get availability
        $product->availability = '';
        if (($product->stock < 1 && CHECK_STOCK) || $product->availableDate > time() ) {
            $product->availability.= $VM_LANG->_('PHPSHOP_CURRENTLY_NOT_AVAILABLE').' ';
        }
        if ($product->availableDate > time() ) {
            $product->availability.= $VM_LANG->_('PHPSHOP_PRODUCT_AVAILABLE_AGAIN').date("d.m.Y", $product->availableDate );
        }
        elseif( ($product->stock >= 1 && CHECK_STOCK) ) {
            $product->availability.=$VM_LANG->_('PHPSHOP_PRODUCT_FORM_IN_STOCK').': '.$product->stock;
        }

        //Get shipping info
        if(CHECK_STOCK && !$product->stock ) {
            $product->shipping = 'not_available.gif';
        }
        if(JFile::exists( VM_THEMEPATH.'images'.DS.'availability'.DS.$product->shipping)) {
            $product->shipping = vmCommonHTML::imageTag( VM_THEMEURL."images/availability/".$product->shipping, JText::_('Shipping info') );
        }

        //Get add to cart form
        list($attributes,$cartType) = $ps_product_attribute->list_attribute(($row->f('product_parent_id')>0)?$row->f('product_parent_id'):$productID);
        $product->set('attributes', $attributes);
        $product->set('quantityBox', $ps_product_attribute->show_quantity_box($row->f('product_parent_id'), $productID));

        //Render the form
        ob_start();
        if(JFile::exists(JPATH_SITE.DS.'templates'.DS.$mainframe->getTemplate().DS.'html'.DS.'k2mart'.DS.$layout.'.php')){
            include JPATH_SITE.DS.'templates'.DS.$mainframe->getTemplate().DS.'html'.DS.'k2mart'.DS.$layout.'.php';
        }
        else {
            include JPATH_SITE.DS.'plugins'.DS.'k2'.DS.'k2mart'.DS.'tmpl'.DS.$layout.'.php';
        }
        $contents = ob_get_clean();
        return $contents;


    }
}
